package com.soup.lab.spring.boot.config.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
@EnableConfigurationProperties({SimpleConfiguration.Config.class})
public class SimpleConfiguration {

    @Bean
    @Primary
    public ConfigHolder configHolder(Config config) {
        return new ConfigHolder(config);
    }

    @Bean
    @Qualifier("conditionalConfig")
    @ConditionalOnProperty(prefix = "config-holder", name = "config.threads")
    @ConfigurationProperties(prefix = "config-holder")
    public ConfigHolder conditionalConfigHolder() {
        return new ConfigHolder();
    }

    public static class ConfigHolder {
        private Config config;

        public ConfigHolder() {
        }

        public ConfigHolder(Config config) {
            this.config = config;
        }

        public Config getConfig() {
            return config;
        }

        public void setConfig(Config config) {
            this.config = config;
        }

        @Override
        public String toString() {
            return "ConfigHolder{" +
                    "config=" + config +
                    '}';
        }
    }

    @ConfigurationProperties(prefix = "config")
    public static class Config {
        private String name;
        private Integer threads;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getThreads() {
            return threads;
        }

        public void setThreads(Integer threads) {
            this.threads = threads;
        }

        @Override
        public String toString() {
            return "Config{" +
                    "name='" + name + '\'' +
                    ", threads=" + threads +
                    '}';
        }
    }

}
